import {IS_FOR_QQ, IS_FOR_WX} from "./AppConfig";

window.functions = window.functions || {};


/**
 * 传入秒，回传HH:MM:SS格式的字符串
 * @param second
 * @param isShowHour
 * @returns {string}
 */
window.functions.formatTime = function (second, isShowHour = true) {
  let sec = second % 60;
  let secondStr = sec < 10 ? "0" + sec : sec.toString();
  let minute = Math.floor(second / 60) % 60;
  let minuteStr = minute < 10 ? "0" + minute : minute.toString();
  let hour = Math.floor(Math.floor(second / 60) / 60);
  let hourStr = hour < 10 ? "0" + hour : hour.toString();

  if (isShowHour) {
    return hourStr + ":" + minuteStr + ":" + secondStr;
  } else {
    return minuteStr + ":" + secondStr;
  }
};

/**
 * 取当天日期字符串, 例: 2018-07-06
 * @returns {string}
 */
window.functions.getTodayString = function () {
  let date = new Date();
  let Y = date.getFullYear();
  let M = (date.getMonth() + 1 < 10 ? '0' + (date.getMonth() + 1) : date.getMonth() + 1);
  let D = date.getDate();
  return Y + '-' + M + '-' + D;
};

/**
 * 设置node的cc.Label组件的文本
 * @param node
 * @param string
 */
window.functions.setLabelString = function (node, string) {
  let label = node.getComponent(cc.Label);
  if (label) {
    label.string = string;
  }
};


/**
 * 取node的cc.Label组件的文本
 * @param node
 */
window.functions.getLabelString = function (node) {
  let label = node.getComponent(cc.Label);
  if (label) {
    return label.string;
  } else
    return '';
};

/**
 * 设置node的cc.Sprite组件的spriteFrame
 * @param node
 * @param spriteFrame
 */
window.functions.setSpriteFrame = function (node, spriteFrame) {
  let sprite = node.getComponent(cc.Sprite);
  if (sprite) {
    sprite.spriteFrame = spriteFrame;
  }
};


window.functions.isString = function (foo) {
  return Object.prototype.toString.call(foo) === "[object String]";
};

let _cacheUrlToSpriteTexture = {};
window.functions.setSpriteByUrl = function (sprite, imageUrl, callback) {
  if (imageUrl === undefined || imageUrl === '') {
    return;
  }
  if (_cacheUrlToSpriteTexture[imageUrl] === undefined) {
    if (cc.sys.platform === cc.sys.WECHAT_GAME && IS_FOR_WX) {
      try {
        let image = wx.createImage();
        image.onload = () => {
          try {
            let texture = new cc.Texture2D();
            texture.initWithElement(image);
            texture.handleLoadedTexture();
            let spriteFrame = new cc.SpriteFrame(texture);
            _cacheUrlToSpriteTexture[imageUrl] = spriteFrame;
            sprite.spriteFrame = spriteFrame;
          } catch (e) {
            console.error(e);
            sprite.node.active = false;
          }
        };
        image.src = imageUrl;
        callback && callback();
      } catch (e) {
        console.error(e);
        sprite.node.active = false;
        callback && callback();
      }
    }
    if (cc.sys.platform === cc.sys.WECHAT_GAME && IS_FOR_WX) {
      try {
        let image = qq.createImage();
        image.onload = () => {
          try {
            let texture = new cc.Texture2D();
            texture.initWithElement(image);
            texture.handleLoadedTexture();
            let spriteFrame = new cc.SpriteFrame(texture);
            _cacheUrlToSpriteTexture[imageUrl] = spriteFrame;
            sprite.spriteFrame = spriteFrame;
          } catch (e) {
            console.error(e);
            sprite.node.active = false;
          }
        };
        image.src = imageUrl;
        callback && callback();
      } catch (e) {
        console.error(e);
        sprite.node.active = false;
        callback && callback();
      }
    } else {
      cc.loader.load({
        url: imageUrl, type: 'jpg'
      }, (err, texture) => {
        let spriteFrame = new cc.SpriteFrame(texture);
        _cacheUrlToSpriteTexture[imageUrl] = spriteFrame;
        sprite.spriteFrame = spriteFrame;
        callback && callback();
      });
    }
  } else {
    sprite.spriteFrame = _cacheUrlToSpriteTexture[imageUrl];
    callback && callback();
  }
};


/**
 * 设置sprite的spriteFrame, 并按size等比缩放
 * @param sprite
 * @param spriteFrame
 * @param size
 */
window.functions.setSpriteFrameAndUniformScale = function (sprite, spriteFrame, size) {
  if (spriteFrame) {
    sprite.spriteFrame = spriteFrame;
    let spriteFrameSize = spriteFrame.getOriginalSize();
    let scale;
    if (spriteFrameSize.width > spriteFrameSize.height) {
      scale = size.width / spriteFrameSize.width;
    } else {
      scale = size.height / spriteFrameSize.height;
    }
    sprite.node.scale = scale;
    return scale;
  }
};


/**
 * 异步读取场景并运行
 * @param sceneName
 */
window.functions.loadingRunScene = function (sceneName) {
  Global.Waiting.show();
  cc.director.preloadScene(sceneName, function () {
    cc.director.loadScene(sceneName, () => {
      console.log("进入场景:", sceneName);
      Global.Waiting.hide();
    });
  });
};


/**
 * 从数组返回随机元素
 * @param array
 * @param remove
 */
window.functions.getRandomElementFromArray = function (array, remove = false) {
  let index = Math.floor(Math.random() * array.length);
  let result = array[index];
  if (remove) {
    array.splice(index, 1);
  }
  return result;
};


/**
 * 判断val是否是js对象
 * @param val
 * @returns {boolean}
 */
window.functions.isObject = function (val) {
  return val != null && typeof val === 'object' && Array.isArray(val) === false;
};


/**
 * 取node的世界旋转
 * @param node
 * @returns {Number|*}
 */
window.functions.getWorldRotation = function (node) {
  let rot = node.rotationX;
  let parent = node.parent;
  while (parent.parent) {
    rot += parent.rotationX;
    parent = parent.parent;
  }
  return rot;
};


window.functions.setWorldRotation = function (worldRot, node) {
  if (node.parent) {
    let parentWorldRot = functions.getWorldRotation(node.parent);
    node.rotation = worldRot - parentWorldRot;
  } else {
    node.rotation = worldRot;
  }
};

/**
 * 强制对齐widget, 并关闭widget组件
 * @param node
 * @param recursion
 */
window.functions.updateWidgetAlignment = function (node, recursion = false) {
  if (node) {
    let widget = node.getComponent(cc.Widget);
    if (widget) {
      widget.updateAlignment();
      widget.enabled = false;
    }
    if (recursion) {
      let count = node.childrenCount;
      for (let i = 0; i < count; i++) {
        let child = node.children[i];
        window.functions.updateWidgetAlignment(child, true);
      }
    }
  }
};

let tmp_quat1 = cc.quat();
let tmp_quat2 = cc.quat();
let tmp_quat3 = cc.quat();
/**
 * 模拟unity3d 的slerp球形插值算法, 用来计算插值旋转
 * @param fromRot
 * @param toRot
 * @param t
 */
window.functions.slerpRotation = function (fromRot, toRot, t) {
  cc.vmath.quat.fromEuler(tmp_quat1, 0, 0, -fromRot);
  cc.vmath.quat.fromEuler(tmp_quat2, 0, 0, -toRot);
  cc.vmath.quat.slerp(tmp_quat3, tmp_quat1, tmp_quat2, t);
  return -tmp_quat3.getYaw();
};


/**参数说明：
 * 根据长度截取先使用字符串，超长部分追加…
 * str 对象字符串
 * len 目标字节长度
 * 返回值： 处理结果字符串
 */

window.functions.cutString = function (str, len) {
  //length属性读出来的汉字长度为1
  if (str.length * 2 <= len) {
    return str;
  }
  let strLen = 0;
  let s = "";
  for (let i = 0; i < str.length; i++) {
    s = s + str.charAt(i);
    if (str.charCodeAt(i) > 128) {
      strLen = strLen + 2;
      if (strLen >= len) {
        return s.substring(0, s.length - 1) + "...";
      }
    } else {
      strLen = strLen + 1;
      if (strLen >= len) {
        return s.substring(0, s.length - 2) + "...";
      }
    }
  }
  return s;
};

/**
 * 返回节点的方向向量
 * @param node
 * @param forwardVec  代表前方的矢量, 例如有时sprite在旋转为0时, 图片是向上的, 此时可设置forwardVec为(1,0), 来修正
 */
window.functions.getNodeDirection = function (node, forwardVec = cc.v2(1, 0)) {
  return forwardVec.rotate(cc.misc.degreesToRadians(-node.rotation));
};

/**
 * 检测目标是否在指定方向的扇形范围内
 * @param selfDir   源方向
 * @param selfPos   源位置
 * @param targetPos 目标位置
 * @param maxAngle  扇形角度
 * @param maxDistance 最大距离
 * @param minDistance 最小距离(可选)
 * @returns {boolean}
 */
window.functions.checkInSector = function (selfDir, selfPos, targetPos, maxAngle, maxDistance, minDistance = undefined) {
  let posDt = targetPos.sub(selfPos);
  let enemyDir = posDt.normalize();
  // let angle = cc.misc.radiansToDegrees(selfDir.signAngle(enemyDir));
  let angle = cc.misc.radiansToDegrees(selfDir.angle(enemyDir));
  // if (angle < 0) {
  //   angle = 360 + angle;
  // }

  // cc.log("夹角", angle);
  if (angle > maxAngle * 0.5) {
    return false;
  }
  let distance = posDt.mag();
  if (distance <= maxDistance) {
    return (minDistance !== undefined) ? distance >= minDistance : true;
  }
  return false;
};


window.functions.loadSubpackage = function (packageName, callback) {
  if (cc.sys.platform === cc.sys.WECHAT_GAME) {
    Global.PlatformUtils.sendLogEvent('加载开始分包资源:' + packageName);
    let retryTimes = 0;
    let loadSubpackage = () => {
      if(IS_FOR_WX){
        wx.loadSubpackage({
          name: packageName,
          success: function (res) {
            Global.PlatformUtils.sendLogEvent('加载开始分包资源成功:' + packageName);
            callback && callback(null);
          },
          fail: function (res) {
            Global.PlatformUtils.sendLogEvent('加载开始分包资源失败:' + packageName, res);
            retryTimes++;
            Global.PlatformUtils.sendLogEvent(`重新加载分包:${packageName},第${retryTimes}次`);
            loadSubpackage();
          }
        });
      }
      else if(IS_FOR_QQ){
        qq.loadSubpackage({
          name: packageName,
          success: function (res) {
            Global.PlatformUtils.sendLogEvent('加载开始分包资源成功:' + packageName);
            callback && callback(null);
          },
          fail: function (res) {
            Global.PlatformUtils.sendLogEvent('加载开始分包资源失败:' + packageName, res);
            retryTimes++;
            Global.PlatformUtils.sendLogEvent(`重新加载分包:${packageName},第${retryTimes}次`);
            loadSubpackage();
          }
        });
      }
    };
    loadSubpackage();
  } else {
    callback && callback(null);
  }
};